﻿using Core.IServices;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Core.Messages;
using Core.Dtos;
using Core.Domain;
using Core.Queries;
using Core.IRepository;
using Core.Mappers;
using Library.Helpers;
using Library.Cache;
using Library.Logging;
using AutoMapper;
using Core.Aspects;

namespace Services
{
    public sealed class GenericReaderService<TId, TEntity, TDto, TQuery> : BaseService, IManageReadService<TId, TDto, TQuery>, IGenericReaderService<TId,TEntity,TDto,TQuery>
        where TDto : BaseDto<TId>
        where TEntity : IBaseEntity<TId>
        where TQuery : Query<TEntity>
    {
        private IUnitOfWork unitOfWork;
        private IRepository<TId, TEntity> repository;

        public void Initialize(IUnitOfWork unitOfWork, IRepository<TId, TEntity> repository)
        {
            this.unitOfWork = unitOfWork;
            this.repository = repository;
        }

        public GenericReaderService()
        {            
        }
        
        public TDto FindByID(TId id)
        {
            TEntity entity = repository.FindBy(id);
            return entity.Map<TDto>();
        }

        [HandleServiceError]
        public QueryResponse<TDto> FindBy(Request<TQuery> request)
        {
            TQuery query = request.Value;
            query = query ?? (TQuery)Activator.CreateInstance(typeof(TQuery));
            QueryResponse<TDto> response = new QueryResponse<TDto>();

            response = repository.FindBy(query).Map<TEntity, TDto>();
            //response.Success = true;
            return response;
        }
    }
}